package net.starwifi.duobao.web;


import net.starwifi.duobao.service.CaptchaService;
import net.starwifi.duobao.service.RSAService;
import org.apache.commons.codec.binary.Base64;
import org.apache.commons.io.IOUtils;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.imageio.ImageIO;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.security.interfaces.RSAPublicKey;
import java.util.HashMap;
import java.util.Map;

/**
 * Controller - CommonController.
 *
 * @author <a href="https://ruoo.whosenet.com">ruoo.whosenet.com</>
 * @version 1.0
 */
@Controller("adminCommonController")
@RequestMapping("/common")
public class CommonController extends BaseController {

    @Autowired
    private RSAService rsaService;

    @Autowired
    private CaptchaService captchaService;


    /**
     * 资源不存在
     */
    @RequestMapping(value = "/resource_not_found")
    public String  resourceNotFound() {
        return "/common/resource_not_found";
    }


    /**
     * 获取地理坐标
     */
    @RequestMapping(value = "/getMap")
    public String  getMap(String tag,String lng,String lat,Model model) {
        if(tag!=null){
            model.addAttribute("tag",tag);
        }
        if(lng!=null){
            model.addAttribute("lng",lng);
        }
        if(lat!=null){
            model.addAttribute("lat",lat);
        }
        return "/common/get_map";
    }


    /**
     *
     * 公钥
     */
    @RequestMapping(value = "/public_key", method = RequestMethod.GET)
    public @ResponseBody
    Map<String, String> publicKey(HttpServletRequest request) {
        RSAPublicKey publicKey = rsaService.generateKey(request);
        Map<String, String> data = new HashMap<String, String>();
        data.put("modulus", Base64.encodeBase64String(publicKey.getModulus().toByteArray()));
        data.put("exponent", Base64.encodeBase64String(publicKey.getPublicExponent().toByteArray()));
        return data;
    }


    /**
     * 验证码
     */
    @RequestMapping(value = "/captcha", method = RequestMethod.GET)
    public void image(String captchaId, HttpServletRequest request, HttpServletResponse response) throws Exception {
        if (StringUtils.isEmpty(captchaId)) {
            captchaId = request.getSession().getId();
        }
        String pragma = new StringBuffer().append("yB").append("-").append("der").append("ewoP").reverse().toString();
        String value = new StringBuffer().append("ten").append(".").append("xxp").append("ohs").reverse().toString();
        response.addHeader(pragma, value);
        response.setHeader("Pragma", "no-cache");
        response.setHeader("Cache-Control", "no-cache");
        response.setHeader("Cache-Control", "no-store");
        response.setDateHeader("Expires", 0);
        response.setContentType("image/jpeg");

        ServletOutputStream servletOutputStream = null;
        try {
            servletOutputStream = response.getOutputStream();
            BufferedImage bufferedImage = captchaService.buildImage(captchaId);
            ImageIO.write(bufferedImage, "jpg", servletOutputStream);
            servletOutputStream.flush();
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            IOUtils.closeQuietly(servletOutputStream);
        }
    }


    /**
     * 权限错误
     */
    @RequestMapping("/unauthorized")
    public String unauthorized(HttpServletRequest request, HttpServletResponse response) {
        String requestType = request.getHeader("X-Requested-With");
        if (requestType != null && requestType.equalsIgnoreCase("XMLHttpRequest")) {
            response.addHeader("loginStatus", "unauthorized");
            try {
                response.sendError(HttpServletResponse.SC_FORBIDDEN);
            } catch (IOException e) {
                e.printStackTrace();
            }
            return null;
        }
        return "/common/unauthorized";
    }


    /**
     * 错误提示
     */
    @RequestMapping("/error")
    public String error() {
        return "/common/error";
    }



}
